﻿"""
生产管理相关API
"""
from flask import Blueprint, jsonify, request
from app.services.production_service import ProductionService
from app.utils.response import success_response, error_response
from app.utils.auth import require_auth
import logging

logger = logging.getLogger(__name__)
production_bp = Blueprint('production', __name__, url_prefix='/yonbip/mfg')


@production_bp.route('/productionorder/list', methods=['POST'])
@require_auth
def get_production_order_list():
    """生产订单列表查询 - 用友云标准接口"""
    try:
        data = request.get_json() or {}

        # 用友云标准参数
        page_index = data.get('pageIndex', 1)
        page_size = data.get('pageSize', 20)

        # 可选查询参数
        code = data.get('code', '')
        status = data.get('status', '')
        trans_type_id = data.get('transTypeId', [])
        org_id = data.get('orgId', [])
        is_show_process = data.get('isShowProcess', 0)
        is_show_material = data.get('isShowMaterial', False)
        is_show_by_product = data.get('isShowByProduct', False)
        is_show_activity = data.get('isShowActivity', False)
        simple = data.get('simple', {})
        simple_vos = data.get('simpleVOs', [])

        logger.info(f"生产订单列表查询: pageIndex={page_index}, pageSize={page_size}, code={code}")

        result = ProductionService.get_order_list(
            page_index=page_index,
            page_size=page_size,
            code=code,
            status=status,
            is_show_process=is_show_process,
            is_show_material=is_show_material,
            is_show_by_product=is_show_by_product,
            is_show_activity=is_show_activity
        )

        # 返回用友云标准格式
        return jsonify({
            "code": "200",
            "message": "操作成功",
            "data": result
        })

    except Exception as e:
        logger.error(f"订单列表查询异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"查询失败: {str(e)}",
            "data": None
        }), 500


@production_bp.route('/productionorder/detail', methods=['GET'])
@require_auth
def get_production_order_detail():
    """生产订单详情查询
    兼容三种入参：
    - id: 长整型订单ID（优先）
    - code: 订单编码（次优先）
    - order_id: 旧格式（ORDxxxx），用于回退生成器
    """
    try:
        order_id = request.args.get('order_id')
        legacy_id = request.args.get('id')
        code = request.args.get('code')

        if not (order_id or legacy_id or code):
            return error_response("订单ID不能为空", code="400"), 400

        numeric_id = None
        if legacy_id and str(legacy_id).isdigit():
            try:
                numeric_id = int(legacy_id)
            except Exception:
                numeric_id = None

        logger.info(f"订单详情查询: order_id={order_id}, id={legacy_id}, code={code}")

        detail = ProductionService.get_order_detail(order_id or "", code=code, numeric_id=numeric_id)
        return success_response("查询成功", detail)

    except Exception as e:
        logger.error(f"订单详情查询异常: {str(e)}")
        return error_response(f"查询失败: {str(e)}"), 500
@production_bp.route('/finishedreport/new/save', methods=['POST'])
@require_auth
def production_completion_save():
    """完工报告保存（用友标准接口）"""
    try:
        request_data = request.get_json()

        # 提取用友标准data结构
        data = request_data.get('data', {})

        # 验证表头必填字段
        required_header_fields = ['orgCode', 'transTypeId', 'vouchdate', '_status', 'finishedReportDetail']
        for field in required_header_fields:
            if not data.get(field):
                return error_response(f"{field}不能为空", code="400"), 400

        # 验证明细不为空
        details = data.get('finishedReportDetail', [])
        if not details or not isinstance(details, list):
            return error_response("finishedReportDetail必须为非空数组", code="400"), 400

        # 验证明细必填字段
        required_detail_fields = ['productionType', 'quantity', 'inspection', 'orgCode', '_status']
        for idx, detail in enumerate(details):
            for field in required_detail_fields:
                if field not in detail:
                    return error_response(f"明细[{idx}].{field}不能为空", code="400"), 400

        logger.info(f"完工报告: orgCode={data.get('orgCode')}, transType={data.get('transTypeId')}, details={len(details)}个")

        result = ProductionService.save_completion_report(data)

        # 返回用友标准响应格式
        return jsonify({
            "code": "200",
            "message": "操作成功",
            "data": result
        })

    except ValueError as e:
        logger.error(f"完工报告验证失败: {str(e)}")
        return jsonify({
            "code": "400",
            "message": str(e),
            "data": None
        }), 400
    except Exception as e:
        logger.error(f"完工报告异常: {str(e)}")
        return jsonify({
            "code": "500",
            "message": f"完工报告提交失败: {str(e)}",
            "data": None
        }), 500


@production_bp.route('/finishedreport/batch/save', methods=['POST'])
@require_auth
def production_batch_completion_save():
    """批量完工报告保存"""
    try:
        data = request.get_json()

        # 验证必要参数
        if not data.get('reports') or not isinstance(data['reports'], list):
            return error_response("reports必须为报告列表", code="400"), 400

        if len(data['reports']) == 0:
            return error_response("报告列表不能为空", code="400"), 400

        logger.info(f"批量完工报告: 共{len(data['reports'])}个报告")

        result = ProductionService.save_batch_completion_reports(data)
        return success_response("批量完工报告提交成功", result)

    except Exception as e:
        logger.error(f"批量完工报告异常: {str(e)}")
        return error_response(f"批量完工报告提交失败: {str(e)}"), 500


@production_bp.route('/realtime/data/collect', methods=['POST'])
@require_auth
def realtime_data_collect():
    """实时生产数据采集"""
    try:
        data = request.get_json()

        # 验证必要参数
        required_fields = ['device_id', 'order_id']
        for field in required_fields:
            if not data.get(field):
                return error_response(f"{field}不能为空", code="400"), 400

        logger.info(f"实时数据采集: device_id={data['device_id']}, order_id={data['order_id']}")

        result = ProductionService.collect_realtime_production_data(data)
        return success_response("实时数据采集成功", result)

    except Exception as e:
        logger.error(f"实时数据采集异常: {str(e)}")
        return error_response(f"实时数据采集失败: {str(e)}"), 500


@production_bp.route('/process/finishedreport/save', methods=['POST'])
@require_auth
def process_completion_save():
    """工序级完工报告保存"""
    try:
        data = request.get_json()

        # 验证必要参数
        required_fields = ['order_id', 'process_id', 'process_name', 'completed_quantity']
        for field in required_fields:
            if not data.get(field):
                return error_response(f"{field}不能为空", code="400"), 400

        logger.info(f"工序完工报告: order_id={data['order_id']}, process={data['process_name']}, qty={data['completed_quantity']}")

        result = ProductionService.save_process_completion_report(data)
        return success_response("工序完工报告提交成功", result)

    except Exception as e:
        logger.error(f"工序完工报告异常: {str(e)}")
        return error_response(f"工序完工报告提交失败: {str(e)}"), 500


@production_bp.route('/finishedreport/list', methods=['GET'])
@require_auth
def get_completion_reports_list():
    """获取完工报告列表"""
    try:
        # 获取查询参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 20))

        # 可选的过滤参数
        filters = {
            'order_code': request.args.get('order_code', ''),
            'product_name': request.args.get('product_name', ''),
            'quality_grade': request.args.get('quality_grade', ''),
            'shift': request.args.get('shift', ''),
            'start_date': request.args.get('start_date', ''),
            'end_date': request.args.get('end_date', '')
        }

        # 移除空值过滤器
        filters = {k: v for k, v in filters.items() if v}

        logger.info(f"查询完工报告列表: page={page}, page_size={page_size}, filters={filters}")

        result = ProductionService.get_completion_reports_list(page, page_size, filters)
        return success_response("查询成功", result)

    except ValueError as e:
        logger.error(f"完工报告列表参数错误: {str(e)}")
        return error_response(str(e), code="400"), 400
    except Exception as e:
        logger.error(f"查询完工报告列表异常: {str(e)}")
        return error_response(f"查询完工报告列表失败: {str(e)}"), 500


@production_bp.route('/productionorder/status/update', methods=['POST'])
@require_auth
def update_order_status():
    """更新生产订单状态"""
    try:
        data = request.get_json()

        # 验证必要参数
        required_fields = ['order_id', 'new_status']
        for field in required_fields:
            if not data.get(field):
                return error_response(f"{field}不能为空", code="400"), 400

        order_id = data['order_id']
        new_status = data['new_status']
        update_data = data.get('update_data', {})

        logger.info(f"订单状态更新: order_id={order_id}, new_status={new_status}")

        result = ProductionService.update_order_status(order_id, new_status, update_data)
        return success_response("订单状态更新成功", result)

    except ValueError as e:
        logger.error(f"订单状态更新参数错误: {str(e)}")
        return error_response(str(e), code="400"), 400
    except Exception as e:
        logger.error(f"订单状态更新异常: {str(e)}")
        return error_response(f"订单状态更新失败: {str(e)}"), 500
